const ws = require("nodejs-websocket")
const puppeteer = require('puppeteer');
const fs = require('fs')

async function serviceStart() {

    var browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] });
    var conns = {};
    var pages = {};

    browser.on('disconnected', async () => {
        browser = await puppeteer.launch({ headless: false });
        browser.on('disconnected', async () => {
            browser = await puppeteer.launch({ headless: false });
        })
    })

    const onText = (text, RoomId) => { }

    const startRoomPage = async (page, RoomConn, RoomId) => {
    	
    		//await Promise.all([
				//  page.goto('https://example.com/', {timeout}),
			 //	 page.waitFor('body', {timeout})
				//])
    	  await page.setDefaultNavigationTimeout(0);
        await page.goto(`https://live.douyin.com/${RoomId}`);
        await page.setRequestInterception(true);
        await page.setCacheEnabled(false);
        await page.exposeFunction('sendRoomMesssage', a => {
						
            if (a.common.method == 'WebcastChatMessage') {
                const data = {
                    Method: a.common.method,
                    roomId: a.common.roomId,
                    UserId: a.user.id,
                    NickName: a.user.nickname,
                    AvatarThumb: a.user.avatarThumb.urlList[0],
                    Content: a.content
                };
                //console.log(JSON.stringify(data));
                RoomConn.send(JSON.stringify(data))
            } 
            if (a.common.method == 'WebcastGiftMessage') {
                const data = {
                    Method: a.common.method,
                    roomId: a.common.roomId,
                    UserId: a.user.id,
                    NickName: a.user.nickname,
                    AvatarThumb: a.user.avatarThumb.urlList[0],
                    GiftId: a.giftId,
                    GiftName: a.gift.name,
                    GiftCount: a.repeatCount
                };
                //console.log(JSON.stringify(data));
                RoomConn.send(JSON.stringify(data))
            }
        }
        );

        await page.exposeFunction('sendRoomError', a => { }
            // RoomConn.send(JSON.stringify(a))
        );

        page.on('request', (request) => {
            if (request.url().indexOf('common-utils-message') != -1) {
                console.log('拦截关键脚本:', request.url());
                request.respond({
                    status: 200,
                    headers: {
                        'Access-Control-Allow-Origin': '*',
                    },
                    contentType: 'application/javascript',
                    body: fs.readFileSync('./dd.js', 'utf-8')
                });
                console.log('已替换:', request.url());
            } else {
                request.continue();
            }
        });
        page.reload();
    }

    const SocketServer = ws.createServer(function (conn) {
    		
        const RoomId = conn.headers.roomid;
        //console.log('连接:',conn);
        if (!RoomId) {
            conn.close()
        } else {
            console.log('RoomdId:', RoomId, ' join...')
            conn.on("text", (text) => onText(text, RoomId))
            conn.on("close", (code, reason) => pages[RoomId].close())
            conn.on("error", (code, reason) => {console.log(code+reason);}) 
            conns[RoomId] = conn; 
    				
            browser.newPage().then((res) => {
                pages[RoomId] = res;
                startRoomPage(pages[RoomId], conn, RoomId);
            });
        }
    }).listen(8001)
}

serviceStart();